package com.self.lock;

import java.util.concurrent.TimeUnit;

public class SelfCountDownLatch {

    private int count;

    public SelfCountDownLatch(int count) {
        this.count = count;
    }

    public synchronized void countDown() {
        this.count--;
        if(this.count <= 0) {
            notifyAll();
        }
    }

    public void await() throws InterruptedException {
        await(0,TimeUnit.MILLISECONDS);
    }

    public void await(long timeout, TimeUnit timeUnit) throws InterruptedException {

        if(this.count <= 0) {
            return;
        }

        if(timeout < 0) {
            timeout = 0;
        }

        synchronized (this) {
            if(this.count <= 0) {
                return;
            }
            while (this.count > 0) {
                wait(timeUnit.toMillis(timeout));
            }
        }
    }

}
